#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
'''

import sys

sys.path.append('/mnt/moonbrook/Moonbrook')
from aes import contact_aes, name_aes
import os
import re
import json
import time
import requests
from copy import deepcopy
from datetime import datetime, timedelta
from apscheduler.schedulers.blocking import BlockingScheduler

from base import ExportAndTjBase
from models import MongoQueryConfig, RobotConfig
from utils import Utils
from robot import DingtalkRobot

reload(sys)
sys.setdefaultencoding('utf-8')


class ExportAndTj(ExportAndTjBase):
    week_min, week_max = Utils.get_date_range(ndays=1,end_time="2022-02-20")
    def __init__(self, *args, **kwargs):
        super(ExportAndTj, self).__init__(*args, **kwargs)
        # todo other col
        self.silk_icp_col = self.silk_db.get_collection('icp')
        self.silk_ent_col = self.silk_db.get_collection('enterprise')



    def handle_one_mongo_data(self, record_dic, save_result_dic=None):
        # 解密，提取字段数据
        nameId = record_dic.get('nameId','')
        must_exists_values = [nameId]  # 这些字段都必须是非空值
        must_has_one_exists_values = []  # 这些字段必须最少有一个是非空值
        if not self.is_data_legal(must_exists_values, must_has_one_exists_values):
            return save_result_dic
        save_result_dic['create_one_day'] += 1
        # if self.silk_ent_col.find_one({'_id':nameId,"crawl_time.1333":  {"$lte": self.week_max, "$gte": self.week_min}},['_id']):
        if self.silk_ent_col.find_one({'_id':nameId,"crawl_time.1333":  {"$exists":True}},['_id']):
            save_result_dic['sent_md_one_day'] += 1
        else:
            self.write_dc_f.write('{}\n'.format(nameId))
        return save_result_dic

    def run(self):
        # 需要统计的维度
        save_result_dic = {
            'sent_md_one_day':0, # 每日推送的名单数
            'create_one_day':0, # icp新增数
        }
        config = {
            MongoQueryConfig.col_name: 'icp',
            MongoQueryConfig.filter: {
                "nameId": {"$exists":True},
                "create_time": {"$lte": self.week_max, "$gte": self.week_min},
                'icpList.domain': {"$exists": True},
                "icp_failed_no":{"$lt":3}
            },
            MongoQueryConfig.projection: ['nameId'],
        }

        result_dic = self.get_data_from_mongo(config, save_result_dic,is_silk=True)


def run(file_name):
    # py文件名/file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__)
    export_and_tj = ExportAndTj(abs_file_name)
    export_and_tj.main()


def scheduler_run(file_name):
    # py文件名/file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__)
    scheduler = BlockingScheduler()
    scheduler.add_job(func=run, trigger='cron',
                      args=(abs_file_name,),
                      # day_of_week="sun",
                      hour='20', minute='52', id='dd_run')
    scheduler.start()


if __name__ == '__main__':
    file_name = '官网统计'
    run(file_name)
    # scheduler_run(file_name)
